package org.study.plus.boot.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.study.plus.boot.mapper.ReportTemplateMapper;
import org.study.plus.boot.mapper.ReportTemplateVersionMapper;
import org.study.plus.boot.model.ReportTemplate;
import org.study.plus.boot.model.ReportTemplateVersion;
import org.study.plus.boot.vo.ReportTemplateDTO;

import java.time.LocalDateTime;

/**
 * 报表模板信息
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年08月19日
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Service
public class ReportTemplateServiceImpl extends ServiceImpl<ReportTemplateMapper, ReportTemplate> implements ReportTemplateService {
    private final ReportTemplateVersionMapper reportTemplateVersionMapper;

    @Override
    public boolean addReportTemplate(ReportTemplateDTO reportTemplateDTO) {
        // 校验
        /*Long nameCount = baseMapper.selectCount(
                Wrappers.<ReportTemplate>query().lambda()
                        .eq(ReportTemplate::getTemplateName, reportTemplateDTO.getTemplateName())
                        .eq(ReportTemplate::getIsDeleted, 0)
        );
        if (0 != nameCount) {
            throw new RuntimeException("模板名称重复");
        }*/
        // 新增
        ReportTemplate reportTemplate = new ReportTemplate();
        BeanUtils.copyProperties(reportTemplateDTO, reportTemplate);
        // reportTemplate.setId(null);
        reportTemplate.setTemplateVersion(1);
        reportTemplate.setIsDeleted(0);
        reportTemplate.setCreateUserId(0L);
        reportTemplate.setCreateUserName("test");
        reportTemplate.setCreateTime(LocalDateTime.now());
        baseMapper.insert(reportTemplate);
        return true;
    }

    @Override
    public boolean updateReportTemplate(ReportTemplateDTO reportTemplateDTO) {
        /*Long nameCount = baseMapper.selectCount(
                Wrappers.<ReportTemplate>query().lambda()
                        .eq(ReportTemplate::getTemplateName, reportTemplateDTO.getTemplateName())
                        .eq(ReportTemplate::getIsDeleted, 0)
                        .ne(ReportTemplate::getId, reportTemplateDTO.getId())
        );
        if (0 != nameCount) {
            throw new RuntimeException("模板名称重复");
        }*/
        // 修改
        ReportTemplate reportTemplate = new ReportTemplate();
        BeanUtils.copyProperties(reportTemplateDTO, reportTemplate);
        reportTemplate.setId(reportTemplateDTO.getId());
        reportTemplate.setUpdateUserId(0L);
        reportTemplate.setUpdateUserName("test");
        reportTemplate.setUpdateTime(LocalDateTime.now());
        if (Boolean.TRUE.equals(reportTemplateDTO.getNewVersion())) {
            ReportTemplate existReportTemplate = baseMapper.selectById(reportTemplateDTO.getId());
            Integer templateVersion = 1;
            // 另存为新版本时，取出最大版本号然后再加1
            Integer maxVersion = reportTemplateVersionMapper.selectTemplateMaxVersion(reportTemplateDTO.getId());
            if (maxVersion != null) {
                // 存在版本号，就取当前版本和历史版本的最大值加1
                templateVersion = maxVersion + 1;
                if (existReportTemplate.getTemplateVersion() >= maxVersion) {
                    templateVersion = existReportTemplate.getTemplateVersion() + 1;
                }
            } else {
                // 不存在历史版本，就是当前版本号加1
                templateVersion = existReportTemplate.getTemplateVersion() + 1;
            }
            reportTemplate.setTemplateVersion(templateVersion);
            int updated = baseMapper.updateById(reportTemplate);
            if (updated > 0) {
                ReportTemplateVersion reportTemplateVersion = ReportTemplateVersion.builder()
                        .templateId(reportTemplateDTO.getId())
                        .templateName(existReportTemplate.getTemplateName())
                        .templateContent(existReportTemplate.getTemplateContent())
                        .templateVersion(existReportTemplate.getTemplateVersion())
                        .createUserId(0L)
                        .createUserName("test")
                        .createTime(LocalDateTime.now())
                        .build();
                reportTemplateVersionMapper.insert(reportTemplateVersion);
            }
        } else {
            // 不修改版本号
            reportTemplate.setTemplateVersion(null);
            baseMapper.updateById(reportTemplate);
        }
        return true;
    }

    @Override
    public boolean rollbackReportTemplateVersion(Long templateVersionId) {
        ReportTemplateVersion reportTemplateVersion = reportTemplateVersionMapper.selectById(templateVersionId);
        if (reportTemplateVersion != null) {
            ReportTemplate reportTemplate = new ReportTemplate();
            BeanUtils.copyProperties(reportTemplateVersion, reportTemplate);
            reportTemplate.setId(reportTemplateVersion.getTemplateId());
            reportTemplate.setIsDeleted(0);
            reportTemplate.setUpdateUserId(0L);
            reportTemplate.setUpdateUserName("test");
            reportTemplate.setUpdateTime(LocalDateTime.now());
            int updated = baseMapper.updateById(reportTemplate);
            if (updated > 0) {
                // 回滚之后，删除该历史版本记录
                reportTemplateVersionMapper.deleteById(templateVersionId);
            }
            return true;
        }
        throw new RuntimeException("该版本不存在，回滚失败");
    }

    @Override
    public boolean deleteReportTemplateById(Long id) {
        // 删除模板
        int updated = baseMapper.deleteById(id);
        if (updated > 0) {
            // 删除模板的所有历史版本
            reportTemplateVersionMapper.delete(
                    Wrappers.<ReportTemplateVersion>query().lambda()
                            .eq(ReportTemplateVersion::getTemplateId, id)
            );
        }
        return true;
    }
}
